package org.xqyy.eval.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.xqyy.eval.dao.IDeptDao;
import org.xqyy.eval.dao.IDeptGroupDao;
import org.xqyy.eval.dao.IExternalEvalMapperDao;
import org.xqyy.eval.service.IExternalEvalMapperService;

import java.util.List;
import java.util.Map;

/**
 * Created by luoxiaoming on 16-12-25.
 */

@Component
@Transactional(readOnly = true)
public class ExternalEvalMapperService implements IExternalEvalMapperService {

    @Autowired
    private IExternalEvalMapperDao externalEvalMapperDao;
    @Autowired
    private IDeptDao deptDao;

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
    public void add(Map<String, Object> params) {
        String groupCode = (String) params.get("groupCode");
        if (StringUtils.hasLength(groupCode)) {
            List<Map<String, Object>> depts = deptDao.load(params);
            if (depts != null && depts.size() > 0) {
                for (Map<String, Object> dept : depts) {
                    params.put("deptCode", dept.get("code"));
                    boolean flag = externalEvalMapperDao.checkHasExistCurrentRecord(params);
                    if (!flag) {
                        externalEvalMapperDao.add(params);
                    }
                }
            }
        } else if (params.get("deptCode")!=null){
            boolean flag = externalEvalMapperDao.checkHasExistCurrentRecord(params);
            if (flag) {
                throw new RuntimeException("已经存在同样的互评数据，请勿重复添加");
            }
            externalEvalMapperDao.add(params);
        }
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
    public void modify(Map<String, Object> params) {
        externalEvalMapperDao.modify(params);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
    public void delete(Map<String, Object> params) {
        externalEvalMapperDao.delete(params);
    }

    @Override
    public List<Map<String, Object>> load(Map<String, Object> params) {
        List<Map<String,Object>> data = externalEvalMapperDao.load(params);
        return data;
    }
}
